#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

/**
 * Prompt管理器 - 负责加载和管理视觉分析提示词
 */
class PromptManager {
    constructor(projectRoot = '.') {
        this.projectRoot = projectRoot;
        this.promptsPath = path.join(projectRoot, 'prompts.json');
        this.prompts = null;
        this.loadPrompts();
    }

    /**
     * 加载prompts配置文件
     */
    loadPrompts() {
        try {
            if (fs.existsSync(this.promptsPath)) {
                const promptData = JSON.parse(fs.readFileSync(this.promptsPath, 'utf8'));
                // 合并所有类型的prompts
                this.prompts = {};

                // 合并design_analysis_prompts
                if (promptData.design_analysis_prompts) {
                    Object.assign(this.prompts, promptData.design_analysis_prompts);
                }

                // 合并code_generation_prompts
                if (promptData.code_generation_prompts) {
                    Object.assign(this.prompts, promptData.code_generation_prompts);
                }

                // 合并其他可能的prompt类型
                Object.keys(promptData).forEach(key => {
                    if (key !== 'metadata' && typeof promptData[key] === 'object') {
                        Object.assign(this.prompts, promptData[key]);
                    }
                });

                return true;
            } else {
                console.warn('prompts.json文件不存在，使用默认提示词');
                this.prompts = this.getDefaultPrompts();
                this.savePrompts();
                return false;
            }
        } catch (error) {
            console.error('加载prompts.json失败:', error.message);
            this.prompts = this.getDefaultPrompts();
            return false;
        }
    }

    /**
     * 获取默认提示词（备用）
     */
    getDefaultPrompts() {
        return {
            analyze_design_screenshot: "Analyze this design screenshot and provide precise UI element descriptions. Return structured JSON data with exact specifications for position, dimensions, colors, typography, borders, backgrounds, shadows, and border radius. Use exact pixel measurements and hex color codes. Return ONLY valid JSON format.",

            extract_component_hierarchy: "Extract the component hierarchy from this design screenshot. Map nested relationships and return a structured JSON tree with containers, layout components, nesting relationships, reusable patterns, dependencies, and component types. Include type, id/classes, position, dimensions, children array, and key properties.",

            get_exact_layout_specifications: "Extract precise layout specifications from this design screenshot. Return detailed JSON with exact measurements for spacing, margins, padding, alignment, grid systems, responsive breakpoints, positioning methods, z-index layering, and container constraints. All measurements in exact pixels.",

            identify_visual_tokens: "Identify and extract the design system tokens from this screenshot. Return comprehensive JSON documentation of color system, typography scale, spacing system, border radius system, shadow system, border system, and icon system with usage examples and semantic naming conventions.",

            analyze_design_with_precision: "Perform a comprehensive and precise analysis of this design screenshot. Provide detailed JSON output with complete CSS properties for each element. Use exact pixel measurements, hex color codes, detailed font specifications, precise spacing values, interactive states, layout parameters, and all relevant CSS properties. Return as detailed structured JSON.",

            compare_image: "List all UI differences between these two images. Only list real UI differences, ignore shadows or compression artifacts. Focus on content changes, layout modifications, color variations, element additions/removals, text changes, and structural differences. Provide a detailed comparison with specific locations and descriptions of each difference.",

            compare_image_with_bounding_boxes: "List all UI differences between these two images with bounding boxes. Output format: [[x0,y0,x1,y1]] per difference. Only list real UI differences, ignore shadows or compression artifacts. For each difference found, provide the bounding box coordinates in the format [[x0,y0,x1,y1]] where (x0,y0) is the top-left corner and (x1,y1) is the bottom-right corner. Focus on content changes, layout modifications, color variations, element additions/removals, text changes, and structural differences.",

            generate_html_from_prototype: "You are a senior front-end engineer who specialises in pixel-perfect UI implementation. I will upload a web prototype. Please reproduce it as a standards-compliant HTML5 page with vanilla CSS (no frameworks). Requirements: 1. Retain all fonts, colours, spacing, border-radius and shadows exactly as shown; do not add, remove or rewrite any text or icons. 2. Use semantic HTML5 tags (`<header>`, `<nav>`, `<main>`, `<section>`, `<footer>`). 3. Use inline styles. 4. The page must use UTF-8 encoding."
        };
    }

    /**
     * 保存prompts到文件
     */
    savePrompts() {
        try {
            const promptData = {
                design_analysis_prompts: this.prompts,
                metadata: {
                    version: "1.0.0",
                    description: "Vision Analyzer Design Analysis Prompts",
                    last_updated: new Date().toISOString().split('T')[0],
                    language: "en",
                    category: "design_analysis"
                }
            };

            fs.writeFileSync(this.promptsPath, JSON.stringify(promptData, null, 2), 'utf8');
            return true;
        } catch (error) {
            console.error('保存prompts.json失败:', error.message);
            return false;
        }
    }

    /**
     * 获取指定的prompt
     * @param {string} promptName - prompt名称
     * @returns {string|null} prompt内容
     */
    getPrompt(promptName) {
        if (!this.prompts) {
            this.loadPrompts();
        }

        return this.prompts.hasOwnProperty(promptName) ? this.prompts[promptName] : null;
    }

    /**
     * 获取所有可用的prompt名称
     * @returns {string[]} prompt名称列表
     */
    getAvailablePrompts() {
        if (!this.prompts) {
            this.loadPrompts();
        }

        return Object.keys(this.prompts);
    }

    /**
     * 更新指定的prompt
     * @param {string} promptName - prompt名称
     * @param {string} promptContent - prompt内容
     * @returns {boolean} 是否更新成功
     */
    updatePrompt(promptName, promptContent) {
        if (!this.prompts) {
            this.loadPrompts();
        }

        this.prompts[promptName] = promptContent;
        return this.savePrompts();
    }

    /**
     * 验证prompt配置完整性
     * @returns {Object} 验证结果
     */
    validatePrompts() {
        const requiredPrompts = [
            'analyze_design_screenshot',
            'extract_component_hierarchy',
            'get_exact_layout_specifications',
            'identify_visual_tokens',
            'analyze_design_with_precision',
            'compare_image',
            'compare_image_with_bounding_boxes'
        ];

        const availablePrompts = this.getAvailablePrompts();
        const missingPrompts = requiredPrompts.filter(name => !availablePrompts.includes(name));

        return {
            isValid: missingPrompts.length === 0,
            availablePrompts,
            missingPrompts,
            totalCount: availablePrompts.length,
            requiredCount: requiredPrompts.length
        };
    }

    /**
     * 重新加载prompts
     */
    reload() {
        this.prompts = null;
        return this.loadPrompts();
    }
}

module.exports = PromptManager;